package cn.edu.ncu.housinghub.controller.message;

import cn.edu.ncu.housinghub.vo.Result;
import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.dto.chat.ChatMessageDTO;
import cn.edu.ncu.housinghub.entity.chatsession.ChatMessage;
import cn.edu.ncu.housinghub.entity.chatsession.ChatSession;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.service.ChatService;
import cn.edu.ncu.housinghub.utils.common.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天REST API控制器
 * 提供HTTP接口用于聊天功能
 */
@RestController
@RequestMapping("/message")
@RequiredArgsConstructor
public class ChatRestController {

    private final ChatService chatService;

    /**
     * 创建或获取聊天会话
     * @param request HTTP请求
     * @param requestBody 请求体
     * @return 会话信息
     */
    @PostMapping("/create-session")
    public Result createSession(HttpServletRequest request, @RequestBody Map<String, Object> requestBody) {
        try {
            // 从token获取当前用户ID
            String token = request.getHeader("info");
            User user = TokenUtil.getUserByToken(token);

            // 检查用户是否存在（token是否有效）
            if (user == null) {
                return Result.error(ErrorCodeConstant.TOKEN_INVALID.getCode(),
                                    ErrorCodeConstant.TOKEN_INVALID.getMessage());
            }

            Long currentUserId = user.getId();
            
            // 获取请求参数
            Long targetUserId = Long.valueOf(requestBody.get("targetUserId").toString());
            Long houseId = requestBody.get("houseId") != null ? 
                Long.valueOf(requestBody.get("houseId").toString()) : null;
            
            // 创建或获取会话
            ChatSession session = chatService.getOrCreateSession(currentUserId, targetUserId, houseId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("sessionId", session.getSessionId());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ErrorCodeConstant.CHAT_SESSION_CREATE_ERROR.getCode(),
                                ErrorCodeConstant.CHAT_SESSION_CREATE_ERROR.getMessage() + ": " + e.getMessage());
        }
    }

    /**
     * 发送消息 (REST API方式)
     * @param request HTTP请求
     * @param messageDTO 消息数据
     * @return 发送结果
     */
    @PostMapping("/send")
    public Result sendMessage(HttpServletRequest request, @RequestBody ChatMessageDTO messageDTO) {
        try {
            // 从token获取当前用户ID
            String token = request.getHeader("info");
            User user = TokenUtil.getUserByToken(token);

            // 检查用户是否存在（token是否有效）
            if (user == null) {
                return Result.error(ErrorCodeConstant.TOKEN_INVALID.getCode(),
                                    ErrorCodeConstant.TOKEN_INVALID.getMessage());
            }

            Long senderId = user.getId();
            
            // 发送消息
            ChatMessage message = chatService.sendMessage(senderId, messageDTO);
            
            Map<String, Object> result = new HashMap<>();
            result.put("messageId", message.getMessageId());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ErrorCodeConstant.CHAT_MESSAGE_SEND_ERROR.getCode(),
                                ErrorCodeConstant.CHAT_MESSAGE_SEND_ERROR.getMessage() + ": " + e.getMessage());
        }
    }

    /**
     * 获取用户的聊天会话列表
     * @param request HTTP请求
     * @return 会话列表
     */
    @GetMapping("/sessions")
    public Result getUserSessions(HttpServletRequest request) {
        try {
            // 从token获取当前用户ID
            String token = request.getHeader("info");
            User user = TokenUtil.getUserByToken(token);

            // 检查用户是否存在（token是否有效）
            if (user == null) {
                return Result.error(ErrorCodeConstant.TOKEN_INVALID.getCode(),
                                    ErrorCodeConstant.TOKEN_INVALID.getMessage());
            }

            Long userId = user.getId();

            // 获取用户会话列表
            List<ChatSession> sessions = chatService.getUserSessions(userId);

            return Result.success(sessions);
        } catch (Exception e) {
            return Result.error(ErrorCodeConstant.CHAT_SESSION_LIST_ERROR.getCode(),
                                ErrorCodeConstant.CHAT_SESSION_LIST_ERROR.getMessage() + ": " + e.getMessage());
        }
    }

    /**
     * 获取会话的消息历史
     * @param sessionId 会话ID
     * @param page 页码 (默认1)
     * @param size 每页大小 (默认20)
     * @return 消息列表
     */
    @GetMapping("/session/{sessionId}")
    public Result getSessionMessages(
            @PathVariable Long sessionId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            // 获取会话消息
            List<ChatMessage> messages = chatService.getSessionMessages(sessionId, page, size);
            
            Map<String, Object> result = new HashMap<>();
            result.put("messages", messages);
            result.put("page", page);
            result.put("size", size);
            result.put("total", messages.size()); // 简化实现，实际应该查询总数
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ErrorCodeConstant.CHAT_MESSAGE_HISTORY_ERROR.getCode(),
                                ErrorCodeConstant.CHAT_MESSAGE_HISTORY_ERROR.getMessage() + ": " + e.getMessage());
        }
    }

    /**
     * 标记消息为已读
     * @param request HTTP请求
     * @param requestBody 请求体
     * @return 操作结果
     */
    @PostMapping("/read")
    public Result markAsRead(HttpServletRequest request, @RequestBody Map<String, Object> requestBody) {
        try {
            // 从token获取当前用户ID
            String token = request.getHeader("info");
            User user = TokenUtil.getUserByToken(token);

            // 检查用户是否存在（token是否有效）
            if (user == null) {
                return Result.error(ErrorCodeConstant.TOKEN_INVALID.getCode(),
                                    ErrorCodeConstant.TOKEN_INVALID.getMessage());
            }

            Long userId = user.getId();
            
            // 获取会话ID
            Long sessionId = Long.valueOf(requestBody.get("sessionId").toString());
            
            // 标记为已读
            chatService.markAsRead(sessionId, userId);
            
            return Result.success("标记已读成功");
        } catch (Exception e) {
            return Result.error(ErrorCodeConstant.CHAT_MESSAGE_READ_ERROR.getCode(),
                                ErrorCodeConstant.CHAT_MESSAGE_READ_ERROR.getMessage() + ": " + e.getMessage());
        }
    }

    /**
     * 获取未读消息数量
     * @param request HTTP请求
     * @param sessionId 会话ID
     * @return 未读数量
     */
    @GetMapping("/unread/{sessionId}")
    public Result getUnreadCount(HttpServletRequest request, @PathVariable Long sessionId) {
        try {
            // 从token获取当前用户ID
            String token = request.getHeader("info");
            User user = TokenUtil.getUserByToken(token);

            // 检查用户是否存在（token是否有效）
            if (user == null) {
                return Result.error(ErrorCodeConstant.TOKEN_INVALID.getCode(),
                                    ErrorCodeConstant.TOKEN_INVALID.getMessage());
            }

            Long userId = user.getId();
            
            // 获取未读数量
            int unreadCount = chatService.getUnreadCount(sessionId, userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("unreadCount", unreadCount);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ErrorCodeConstant.CHAT_UNREAD_COUNT_ERROR.getCode(),
                                ErrorCodeConstant.CHAT_UNREAD_COUNT_ERROR.getMessage() + ": " + e.getMessage());
        }
    }

    /**
     * 获取用户的总未读消息数量
     * @param request HTTP请求
     * @return 总未读数量
     */
    @GetMapping("/unread/total")
    public Result getTotalUnreadCount(HttpServletRequest request) {
        try {
            // 从token获取当前用户ID
            String token = request.getHeader("info");
            User user = TokenUtil.getUserByToken(token);

            // 检查用户是否存在（token是否有效）
            if (user == null) {
                return Result.error(ErrorCodeConstant.TOKEN_INVALID.getCode(),
                                    ErrorCodeConstant.TOKEN_INVALID.getMessage());
            }

            Long userId = user.getId();
            
            // 获取用户所有会话
            List<ChatSession> sessions = chatService.getUserSessions(userId);
            
            // 计算总未读数量
            int totalUnread = 0;
            for (ChatSession session : sessions) {
                totalUnread += chatService.getUnreadCount(session.getSessionId(), userId);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("totalUnread", totalUnread);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ErrorCodeConstant.CHAT_TOTAL_UNREAD_ERROR.getCode(),
                                ErrorCodeConstant.CHAT_TOTAL_UNREAD_ERROR.getMessage() + ": " + e.getMessage());
        }
    }
}
